<?php

namespace App\Http\Middleware;

use App\service\JwtService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CheckMiddleware
{
    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //判断token是否存在、并且保证token是有效的才能访问
        $token = $request->header('token');
        if (empty($token)) {
            echo '未登录';
            die();
        }
        $user = JwtService::decodeToken($token);
        if (!$user) {
            throw new \Exception('token无效');
        }
        $id = $user->data->id;
        //限制用户访问接口次数
        $limit = 1;
        $check = Redis::exists('_limit_user' . $id);
        //用户存在
        if ($check) {
            //递增次数
            Redis::incr('_limit_user' . $id);
            $count = Redis::get('_limit_user' . $id);
            if ($count > $limit) {
                throw new \Exception('你的请求过快');
            }
        }
        Redis::incr('_limit_user' . $id);
        //设置过期时间60秒
        Redis::expire('_limit_user' . $id, 60);
        return $next($request);
    }
}
